<template>
  <div class="article-form-container">
    <el-card>
      <template #header>
        <h2>{{ isEditing ? '编辑文章' : '发表新文章' }}</h2>
      </template>
      <el-form :model="articleForm" :rules="rules" ref="formRef" label-width="100px" v-loading="loading">
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- Replace with a rich text editor in a real application -->
          <el-input type="textarea" :rows="10" v-model="articleForm.content" placeholder="请输入文章内容"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ isEditing ? '更新' : '发布' }}</el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'ArticleForm',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const formRef = ref(null) 
    const loading = ref(false)

    const articleId = computed(() => route.params.id)
    const isEditing = computed(() => !!articleId.value)

    const articleForm = reactive({
      title: '',
      content: ''
    })

    const rules = {
      title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 3, max: 150, message: '长度在 3 到 150 个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' },
        { min: 10, message: '内容至少需要 10 个字符', trigger: 'blur' }
      ]
    }

    const fetchArticleData = async () => {
      if (isEditing.value) {
        loading.value = true
        try {
          const response = await axios.get(`/api/articles/${articleId.value}`)
          articleForm.title = response.data.title
          articleForm.content = response.data.content
        } catch (error) {
          ElMessage.error('获取文章数据失败')
          console.error(error)
          router.push('/articles') // Redirect if article not found or error
        } finally {
          loading.value = false
        }
      }
    }

    const submitForm = async () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const token = localStorage.getItem('token')
            if (isEditing.value) {
              await axios.put(`/api/articles/${articleId.value}`, articleForm, {
                headers: { Authorization: `Bearer ${token}` }
              })
              ElMessage.success('文章更新成功')
            } else {
              await axios.post('/api/articles', articleForm, {
                headers: { Authorization: `Bearer ${token}` }
              })
              ElMessage.success('文章发布成功')
            }
            router.push('/articles')
          } catch (error) {
            ElMessage.error(error.response?.data?.message || (isEditing.value ? '更新失败' : '发布失败'))
            console.error(error)
          } finally {
            loading.value = false
          }
        }
      })
    }

    onMounted(() => {
      fetchArticleData()
    })

    return {
      articleForm,
      rules,
      isEditing,
      loading,
      formRef,
      submitForm,
      router
    }
  }
}
</script>

<style scoped>
.article-form-container {
  padding: 20px;
  max-width: 800px;
  margin: auto;
}
</style> 